package com.zhkj.txg.module.member.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.HttpResponseException
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.module.home.ui.BackTabEvent
import com.zhkj.txg.module.member.entity.*
import com.zhkj.txg.module.member.model.MemberManager
import com.zhkj.txg.module.mine.entity.UserCenterResponse
import com.zhkj.txg.module.order.entity.OrderPayResponse
import com.zhkj.txg.utils.PayResult
import io.reactivex.android.schedulers.AndroidSchedulers

class MemberCardViewModel(application: Application) : BaseViewModel(application) {
    private val memberManager = MemberManager()
    private val payResultLiveData = MutableLiveData<PayResult>()
    val memberCardLiveData = MutableLiveData<HttpResponse<MemberCardResponse>>()
    val memberProductListLiveData = MutableLiveData<HttpResponse<MemberProductListResponse>>()
    val memberProductLiveData = MutableLiveData<HttpResponse<MemberProductResponse>>()
    val defaultAddressLiveData = MutableLiveData<HttpResponse<DefaultAddressResponse>>()
    val orderPayLiveData = MutableLiveData<HttpResponse<OrderPayResponse>>()
    val fragmentChangeLiveData = MutableLiveData<Boolean>()
    val totalIncomeLiveData = MutableLiveData<HttpResponse<MemberIncomeResponse>>()
    val interestExpand = MutableLiveData<Boolean>()
    val checkResultLiveData = MutableLiveData<HttpResponse<CheckResultResponse>>()
    val userInfoLiveData = MutableLiveData<HttpResponse<UserCenterResponse>>()

    private var page = 1
    private val numb = 20

    // 会员支付页面UI数据，只有在会员支付页面才会初始化
    var productUIEntity: MemberProductUIEntity? = null
    var inviteCode: String? = null

    fun getMemberCard(
        token: String,
        loadProduct: Boolean = false
    ) {
        val listener = object : ViewModelSubscribeListener<MemberCardResponse>(memberCardLiveData) {
            override fun onSuccess(resp: MemberCardResponse) {
                // 添加会员权益足部
                resp.data?.cardInfo?.let {
                    if (it.interest.isNotEmpty()) it.interest.add(InterestEntity("").apply {
                        itemType = 1
                        expand = true
                    })
                }
                super.onSuccess(resp)
                if (loadProduct) getProductList(token, true)
            }

            override fun onFailure(throwable: Throwable) {
                if (throwable is HttpResponseException && throwable.code == 401) RxBus.post(
                    BackTabEvent()
                )
                super.onFailure(throwable)
            }
        }
        val memberCard = memberManager.memberCard(token, listener)
        dispose.add(memberCard)
    }

    fun getProductList(token: String, restart: Boolean = false) {
        val listener =
            object :
                ViewModelSubscribeListener<MemberProductListResponse>(memberProductListLiveData) {
                override fun onSuccess(resp: MemberProductListResponse) {
                    resp.hasMore = resp.data.size >= numb
                    resp.loadMore = page > 1
                    super.onSuccess(resp)
                    page += 1
                }
            }
        if (restart) page = 1
        val memberProductList = memberManager.memberProductList(token, page, numb, listener)
        dispose.add(memberProductList)
    }

    fun memberProductDetail(productId: Long) {
        val listener = ViewModelSubscribeListener(memberProductLiveData)
        val memberProduct = memberManager.memberProduct(AccountManager.getToken(), productId, listener)
        dispose.add(memberProduct)
    }

    fun defaultAddress() {
        val listener = ViewModelSubscribeListener(defaultAddressLiveData)
        val defaultAddress = memberManager.defaultAddress(AccountManager.getToken(), listener)
        dispose.add(defaultAddress)
    }

    /**
     * 支付结果
     */
    fun payResult(): MutableLiveData<PayResult> {
        val payResult = RxBus.toObservable(PayResult::class.java)
            .subscribeOn(AndroidSchedulers.mainThread()).subscribe({
                payResultLiveData.value = it
            }, {
                it.printStackTrace()
                payResultLiveData.value = PayResult(false, it.message ?: "")
            })
        dispose.add(payResult)
        return payResultLiveData
    }

    fun memberOrderPay(payType: String) {
        defaultAddressLiveData.value?.response?.data?.let {
            val listener = ViewModelSubscribeListener(orderPayLiveData)
            val memberOrderPay =
                memberManager.memberOrderPay(
                    AccountManager.getToken(), productUIEntity?.productId ?: 0, productUIEntity?.productNumber ?: 0,
                    productUIEntity?.specId ?: 0, it.id.toLong(), payType, inviteCode ?: "", listener
                )
            dispose.add(memberOrderPay)
        }
    }

    fun totalIncome() {
        val listener = ViewModelSubscribeListener(totalIncomeLiveData)
        val totalIncome = memberManager.totalIncome(AccountManager.getToken(), listener)
        dispose.add(totalIncome)
    }

    fun checkCode(code: String, uiEntity: MemberProductUIEntity) {
        val listener = object : ViewModelSubscribeListener<CheckResultResponse>(checkResultLiveData) {
            override fun onSuccess(resp: CheckResultResponse) {
                resp.uiEntity = uiEntity
                resp.inviteCode = code
                super.onSuccess(resp)
            }
        }
        val checkCode =
            memberManager.checkCode(AccountManager.getToken(), code, listener)
        dispose.add(checkCode)
    }

    fun userCenter() {
        val listener = ViewModelSubscribeListener(userInfoLiveData)
        val userCenter = memberManager.userCenter(AccountManager.getToken(), listener)
        dispose.add(userCenter)
    }
}